/*
 * ContactDetailTableModel.java
 *
 * Created on 23 November 2003, 04:58
 * Copyright (C) 2003, Velocityme Partnership
 */

package com.velocityme.client.gui.contactdetail;

import com.velocityme.client.gui.VectorTableModel;
import com.velocityme.valueobjects.ContactDetailValue;
import com.velocityme.valueobjects.ContactDetailValueToString;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 *
 * @author  Robert Crida Work
 */
public class ContactDetailTableModel extends VectorTableModel {
    
    private boolean m_editable = false;
    
    /** Creates a new instance of ContactDetailTableModel */
    public ContactDetailTableModel() {
        super(new String[] {"Type", "Value"});
    }
    
    public ContactDetailValue[] getElements() {
        ContactDetailValue[] results = new ContactDetailValue[getRowCount()];
        for (int row = 0; row < getRowCount(); row++) {
            ContactDetailValue value = (ContactDetailValue)getValueAt(row,2); 
            value.setValue((String)getValueAt(row,1));
            results[row] = value;
        }
        return results;
    }
    
    /** Add a new row to the table.
     */
    public void setContactDetails(ContactDetailValue[] p_values) {
        if(p_values == null)return;
        SortedSet sortedSet = new TreeSet();       
        for (int i = 0; i < p_values.length; i++)
            sortedSet.add(new ContactDetailValueToString(p_values[i]));
        Iterator i = sortedSet.iterator();
        m_dataRows.clear();
        while(i.hasNext()) {
            ContactDetailValue value = (ContactDetailValue)i.next();
            m_dataRows.addElement(new Object[]{ value.getContactDetailTypeValue().getName(), value.getValue(), value });
        }
        fireTableRowsInserted(0, m_dataRows.size());
    }
    
    public void setEditable(boolean editable) {
        m_editable = editable;
    }
    
    public boolean isCellEditable(int row, int col) {
        return col == 1 && m_editable;
    }
    
    public Object getValueAt(int row, int col) {
        ContactDetailValue value = (ContactDetailValue)((Object[])m_dataRows.get(row))[2];
        if (col == 0 && !m_editable && !value.getContactDetailTypeValue().getShowType().booleanValue())
            return "";
        return ((Object[])m_dataRows.get(row))[col];
    }
    
    public void setValueAt(Object value, int row, int col) {
        ((Object[])m_dataRows.get(row))[col] = value;
        fireTableDataChanged();
    }
    
}
